package com.bosssoft.hr.train.j2se.file;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * @Class OssFileUtils
 * @Description 利用阿里云上传文件的工具类
 * 其中包含upload(File file) 实现文件流的上传云存储。
 * @Author TangZaoBang
 * @Date 2023/04/27 14:37
 * @Version
 */
@Slf4j
@Data
@NoArgsConstructor
@AllArgsConstructor
public class OssFileUtils {
    /**
     *Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
     */
    private static final String ENDPOINT = "https://oss-cn-hangzhou.aliyuncs.com";
    /**
     *  阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
     */
    private static final String ACCESS_KEY_ID = "LTAI5t9YyGqko75rUodBdbCU";
    /**
     * 密码
     */
    private static final String ACCESS_KEY_SECRET = "aOcc0rHjbd0wt8mckNWSBhGJsO3QFF";
    /**
     * 填写Bucket名称，例如examplebucket。
     */
    private static final String BUCKET_NAME = "tzb-in-bs";
    /**
     * 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
     */
    private String objectName ;
    /**
     *  填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。
     *  如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
     */
    private  String filePath;

    /**
     * 创建存储空间；上传；
     * @author TangZaoBang
     * @date 2023/04/27 17:01
     * @param args
     * @return void
     */
    public static void main(String[] args) {
        OssFileUtils ossFileUtils = new OssFileUtils("C:\\Users\\YOURSLIHUA\\.A-JavaProject\\boss\\tzb\\javaee_basic\\ad.png","C:\\Users\\YOURSLIHUA\\.A-JavaProject\\boss\\tzb\\javaee_basic\\ad.png");
        ossFileUtils.creat();
        ossFileUtils.upload(ossFileUtils.objectName,ossFileUtils.getFilePath());
    }

    /**
     * 上传文件
     * @author TangZaoBang
     * @date 2023/04/27 16:57
     * @param objectName
     * @param filePath
     * @return void
     */
    public  void upload( String objectName,String filePath) {
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        try {
            InputStream inputStream = new FileInputStream(filePath);
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, objectName, inputStream);
            // 设置该属性可以返回response。如果不设置，则返回的response为空。
            putObjectRequest.setProcess("true");
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            // 如果上传成功，则返回200。
            log.info("上传成功");
            log.info(String.valueOf(result.getResponse().getStatusCode()));
        } catch (OSSException oe) {
            oExceptionMsg(oe);
        } catch (ClientException ce) {
            cExceptionMsg(ce);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
    /**
     * 创建储存空间
     * @author TangZaoBang
     * @date 2023/04/27 16:58
     * @return void
     */
    public void creat(){
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        try {
            // 创建存储空间。
            ossClient.createBucket(BUCKET_NAME);
            log.info("创建存储空间成功");
        } catch (OSSException oe) {
           oExceptionMsg(oe);
        } catch (ClientException ce) {
            cExceptionMsg(ce);
        } finally {

                ossClient.shutdown();

        }
    }
    /**
     * 输出OSSException 的错误信息
     * @author TangZaoBang
     * @date 2023/04/27 16:58
     * @param oe OSSException
     * @return void
     */
    public static void oExceptionMsg(OSSException oe) {
        log.info("Caught an OSSException, which means your request made it to OSS, "
                + "but was rejected with an error response for some reason.");
        log.info("Error Message:" + oe.getErrorMessage());
        log.info("Error Code:" + oe.getErrorCode());
        log.info("Request ID:" + oe.getRequestId());
        log.info("Host ID:" + oe.getHostId());
    }

    /**
     * 输出ClientException 的错误信息
     * @author TangZaoBang
     * @date 2023/04/27 16:58
     * @param ce ClientException
     * @return void
     */
    public static void cExceptionMsg(ClientException ce){
        log.info("Caught an ClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with OSS, "
                + "such as not being able to access the network.");
      log.info("Error Message:" + ce.getMessage());
    }

}
